<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <div th:replace="common/header :: metaHeader"></div>
  <title>AdminLTE 2 | Data Tables</title>
  <!-- Bootstrap 3.3.6 -->
  <link rel="stylesheet" th:href="@{/static/bootstrap/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/static/datatables.net-bs/css/datatables.bootstrap.min.css}">
  <!-- Font Awesome -->
  <link rel="stylesheet" th:href="@{/static/font-awesome/css/font-awesome.min.css}">
  <!-- Ionicons -->
  <link rel="stylesheet" th:href="@{/static/Ionicons/css/ionicons.min.css}">
  <!-- Theme style -->
  <link rel="stylesheet" th:href="@{/static/admin-lte/css/AdminLTE.min.css}">
  <!-- AdminLTE Skins. Choose a skin from the css/skins
       folder instead of downloading all of them to reduce the load. -->
  <link rel="stylesheet" th:href="@{/static/admin-lte/css/skins/_all-skins.min.css}">

    <style type="text/css">
        table.dataTable tbody tr.selected {
            background-color: #B0BED9;
        }
    </style>

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>
        Table
        <small>Version 2.0</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">Dashboard</li>
    </ol>
</section>

<!-- Main content -->
<section class="content">
    <div class="box">
        <div class="box-header">
            <h3 class="box-title">Data Table With Full Features</h3>
        </div>
        <!-- /.box-header -->
        <div class="box-body">
            <table id="example1" class="table table-bordered table-striped">
                <thead>
                <tr>
                    <th>No.</th>
                    <th>Rendering engine</th>
                    <th>Browser</th>
                    <th>Platform(s)</th>
                    <th>Engine version</th>
                    <th>options</th>
                </tr>
                </thead>
            </table>
        </div>
        <!-- /.box-body -->
    </div>
    <!-- /.box -->
</section>
<!-- /.content -->

<!-- jQuery -->
<script th:src="@{/static/jquery/jquery.min.js}"></script>
<!-- Bootstrap 3.3.6 -->
<script th:src="@{/static/bootstrap/js/bootstrap.min.js}"></script>
<!-- SlimScroll 1.3.0 -->
<script th:src="@{/static/datatables.net/js/jquery.dataTables.min.js}"></script>
<script th:src="@{/static/datatables.net-bs/js/dataTables.bootstrap.min.js}"></script>
<script>
  //https://www.cnblogs.com/amoniyibeizi/p/4548111.html
  //这里用的是dataTables bootstrap插件样式
  var dataTable1;
  $(function () {
    dataTable1 = $('#example1').DataTable({
      //固定表头
      'bFixedHeader': true,
      //自适应屏幕
      'responsive' : true,
      //60%高
      'scrollY':      '60vh',
      'scrollCollapse': true,
       //列宽自动调整
      'bAutoWidth'      : true,
      //渲染
      'bDeferRender': true,
      //滚动条
      'scroller':       true,
      //显示过滤框
      'bFilter'   : true,
      //显示每页条数设置
      'bLengthChange'    : true,
      //开启分页
      'bPaginate'        : true,
      //'pagingType' : '',
      //显示页码信息
      'bInfo'        : true,
      //列排序
      'bSort'        : true,
      //cookie缓存设置信息
      'bStateSave'  : true,
      //显示加载中
      'bProcessing'   : true,
      //默认每页条数
      'iDisplayLength'   : 15,
      //显示页条数选择框
      'aLengthMenu' : [15, 30, 60, 90],
      //通过服务器获取数据
      'bServerSide': true,
      //调用地址
      /** 不适用该属性
      'sAjaxSource': '/table/data',
      //调用方式定义
      'fnServerData' : function(sSource, aDataSet, fnCallback) {
                                console.log(aDataSet);
                                $.ajax({
                                    'dataType' : 'json',
                                    'type' : 'POST',
                                    'async' : false,
                                    'url' : sSource, //上面配置的调用地址
                                    'data' : aDataSet, //aDataSet此时已经包含附加参数了和其他默认参数,array类型
                                    'success' : fnCallback
                                });
                            },
      //附加参数,配合fnServerData使用
      'fnServerParams': function ( aoData ) {
          aoData.push({ 'name': 'my_key', 'value': 'my_value' });
          aoData.push({ 'name': '_csrf', 'value': '[[${_csrf.token}]]' });//双中括号取thymeleaf变量值
       },
       **/
      'ajax': {//自定义请求参数
            'url': '/table/data',
            'type': 'POST',
            'data': function (d) {
                        //console.log(d);
                        //自定义附加参数
                        d._csrf = '[[${_csrf.token}]]';
                        d.my_key = 'my_value';
                        return d;
                    }
            },
       //语言
      'oLanguage': {
            'sProcessing': 'loading...',
            'sLengthMenu': '显示 _MENU_ 条',
            'sZeroRecords': '没有您要搜索的内容',
            'sInfo': '从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条',
            'sInfoEmpty': '没有数据哦',
            'sInfoFiltered': '(共 _MAX_ 条)',
            'sInfoPostFix': '',
            'sSearch': '搜索',
            'sUrl': '',
            'oPaginate': {
                'sFirst': '第一页',
                'sPrevious': '上一页',
                'sNext': '下一页',
                'sLast': '最后一页'
            }
        },
        //每行回调方法
        'fnRowCallback' : function(nRow, aData, iDisplayIndex) {
                            //console.log('====>' + nRow)
                            //console.log('====>' + aData)
                            //console.log('====>' + iDisplayIndex)
                            //console.log('====>' + aData.enabled)
                            if (aData.enabled == true)
                                $('td:eq(2)', nRow).html('启用');//第三列
                            else
                                $('td:eq(2)', nRow).html('禁用');
                            return nRow;
                        },
        //返回的json列映射
        'aoColumns' : [
                     {
                        'sTitle' : '序号',
                        'mDataProp' : null,
                        'sDefaultContent' : ''
                    },
                    {
                        'mDataProp' : 'id',
                        'sDefaultContent' : '',
                        'bVisible' : false
                    },
                    {
                        'mDataProp' : 'username',
                        'sTitle' : '用户名',
                        'sDefaultContent' : '',
                        'sClass' : 'center'
                    }, {
                        'mDataProp' : 'password',
                        'sTitle' : '密码',
                        'sDefaultContent' : '',
                        'sClass' : 'center'
                    }, {
                        'mDataProp' : 'enabled',
                        'sTitle' : '状态',
                        'sDefaultContent' : '-',
                        'sClass' : 'center'
                    }, {
                        'mDataProp' : null,
                        'sTitle' : '编辑',
                        'sDefaultContent' : '<a onclick="editRow(this)" data-toggle="modal" data-target="#modalRowEdit">edit</a>',
                        'sClass' : 'center'
                    }
                    ]
    });

   $('#example1 tbody').on('click','tr', function (e) {
            //console.log(e);
            /**
            //方式1, jquery方式，但是获取数据只能是table里显示的
            var nTds = $('td', this);
            var colData = {};
            colData.c0 = $(nTds[0]).text();  //得到第1列的值
            colData.c1 = $(nTds[1]).text();
            colData.c2 = $(nTds[2]).text();
            **/
            //方式2，推荐，该方式获取从服务器端传来的原始数据，包含不显示的
            var colData = dataTable1.row(this).data();
            console.log(colData);
            //选中高亮
            if ( $(this).hasClass('selected') ) {
                   $(this).removeClass('selected');
            } else {
                   dataTable1.$('tr.selected').removeClass('selected');
                   $(this).addClass('selected');
            }
     });

     //增加序号列，order.dt search.dt是排序和搜索事件,这两个事件在deferRender-true时候无效
     dataTable1.on('draw.dt', function () {
            //保证分页情况下序号连续
            var pageInfo = dataTable1.page.info();
            dataTable1.column(0, { page: 'current' }).nodes().each( function (cell, i) {
                cell.innerHTML = i + 1 + pageInfo.start;
                //console.log(cell);
            });
     });

     /**$('#button').click( function () {
       //删除选中
        dataTable1.row('.selected').remove().draw( false );
     });**/


    $("#saveBtn").on("click",function(){
                $.ajax({
                    type: 'post',
                    data: $('#userInfo').serialize(),
                    url: '/user/save',
                    cache : false,
                    dataType:'text',
                    success: function (data) {
                        if(200 == data.status){
                            alert('保存成功');
                            //window.location.href = "${ctx}/user/userList?userId="+data;
                        }else{
                            alert('保存失败');
                        }
                    }
                })
            });

  });

  function editRow(obj) {
     //a标签的父标签的父标签是tr
     var colData = dataTable1.row(obj.parentNode.parentNode).data();
     console.log(colData);
     $('#username').val(colData.username);
     $('#password').val(colData.password);
     if (colData.enabled == true) {
        $('#optionsRadios1').attr('checked','checked');
     } else {
        $('#optionsRadios2').attr('checked','checked');
     }
  }
</script>
<div th:fragment="rowEdit" class="modal fade" id="modalRowEdit">
    <!-- form start -->
    <form class="form-horizontal" id="userInfo">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Edit Data</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="username" class="col-sm-2 control-label">Username</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="username" name="username" placeholder="Username">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="password" class="col-sm-2 control-label">Password</label>
                        <div class="col-sm-10">
                            <input type="password" name="password" class="form-control" id="password" placeholder="Password">
                        </div>
                    </div>
                    <!-- radio -->
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <div class="radio">
                                <label>
                                    <input type="radio" name="enabled" id="optionsRadios1" value="1" checked>
                                    Enabled
                                </label>
                                <label>
                                    <input type="radio" name="enabled" id="optionsRadios2" value="0">
                                    Disabled
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="_csrf" th:value="${_csrf.token}">
                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveBtn">Save changes</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
    </form>
    <!-- /.modal-dialog -->
</div>
</body>
</html>
